package com.wangt.biz.controller;

import com.wangt.biz.mqtt.MqttProviderConfig;
import com.wangt.biz.service.MqttService;
import com.wangt.common.core.domain.R;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/mqtt")
public class MqttController {
    @Autowired
    private MqttProviderConfig providerClient;

    @Autowired
    private MqttService mqttService;

    @Value("${spring.mqtt.client.id}")
    private String clientId;

    /**
     * 发布信息
     * @param qos
     * @param retained
     * @param topic
     * @param message
     * @return
     */
    @GetMapping("/sendMessage")
    @ResponseBody
    public String sendMessage(int qos, boolean retained, String topic, String message) {
        try {
            providerClient.publish(qos, retained, topic, message);
            return "发送成功";
        } catch (Exception e) {
            e.printStackTrace();
            return "发送失败";
        }
    }

    /**
     * 动态 订阅  主题的接口
     *
     * @param topic
     * @param qos
     * @return
     */
    @GetMapping("/sub")
    @ResponseBody
    public R sub(String topic, int qos) {
        mqttService.sub(topic, qos);
        return R.ok();
    }
}
